<?php
namespace app\models;

use Yii;
use yii\base\Model;

/**
 * 管理员用户设置
 *
 * Class ManagerProfile
 * @package app\models
 */
class ManagerProfile extends Model
{
    public $id;
    public $username;
    public $new_password;
    public $confirm_password;
    public $nickname;
    public $mobile;
    public $email;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'nickname', 'mobile', 'email'], 'required'],
            [['username', 'mobile', 'email'], 'unique', 'targetClass'=>Manager::className(), 'filter'=>function($query) {/* @var $query \yii\db\Query */$query->andWhere(['<>', 'id', $this->id])->andWhere(['<>', 'status', Manager::STATUS_DELETED]);return $query;}],
            [['new_password', 'confirm_password'], function() {
                if ($this->new_password != $this->confirm_password) {
                    $this->addError('new_password', '两次输入密码不同。');
                }
            }],
        ];
    }

    /**
     * 保存账号设置
     * @return boolean
     */
    public function save()
    {
        $manager = Manager::findOne($this->id);
        $manager->username = $this->username;
        $manager->nickname = $this->nickname;
        $manager->mobile = $this->mobile;
        $manager->email = $this->email;
        if (!empty($this->new_password)) {
            $manager->password = Yii::$app->security->generatePasswordHash($this->new_password);
        }
        if ($manager->save()) {
            // 更新Session
            Yii::$app->manager->setIdentity($manager);
            return true;
        }
        $this->addErrors($manager->errors);
        return false;
    }
}
